using AutoMapper;
using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.BaseLibrary;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Repositories;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Common;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Core.Toolkit.Core.Application;
using Core.Toolkit.Core.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;


namespace Core.SimpleTemp.Application
{
    [AutoDi()]
    public class CBS_BreakRulesService : BaseAppService<CBS_BreakRulesDto, CBS_BreakRules, CBS_BreakRulesRepository>
    {
        readonly TempDirDiHelp _TempDirHelp;
        readonly ExcelHelp _excelHelp;
        CoreDBContext _dbContext;
        readonly UserIdentity _userIdentity;
        readonly Toolkit.Core.Repositories.SQLHelper _helper;
        public CBS_BreakRulesService(CBS_BreakRulesRepository repository, ExcelHelp excelHelp, CoreDBContext dbContext, TempDirDiHelp tempDirHelp, IHttpContextAccessor accessor, Toolkit.Core.Repositories.SQLHelper helper) : base(repository)
        {
            _excelHelp = excelHelp;
            _TempDirHelp = tempDirHelp;
            _dbContext = dbContext;
            _helper = helper;
            if (accessor.HttpContext != null)
            {
                _userIdentity = accessor.HttpContext.User.GetUserIdentity();
            }
        }



        private LoadPageOffsetModelAuto<CBS_BreakRules, CBS_BreakRulesDto> GetLoadPageOffsetMode(PagingModel<CBS_BreakRulesDto> pagingQueryModel)
        {
            var loadPageOffsetModel = this.GetLoadPageOffsetModelAuto(pagingQueryModel);
            this.GetLoadPageOffsetModel(pagingQueryModel);

            //查询条件
            var whereEntity = pagingQueryModel.Model.ToEntity<CBS_BreakRules>();
            var where = this.CreateQRList()

            .Add("CBSListId", "=")
            .Add("AreaID","=")
            //.Add("ViolationDate", "=")
            //.Add("ViolationInstructions", "=")
            //.Add("ViolatorsID", "=")
            //.Add("ViolationClause", "=")
            //.Add("DiscoveringPeopleID", "=")
            //.Add("Remarks", "=")
            //.Add("ProcessingOpinion", "=")
            //.Add("ProcessingResult", "=")
            //.Add("ExamineState", "=")
            //.Add("ExamineUser", "=")
            //.Add("ContractorQZ", "=")
            //.Add("CreateFactory", "=")
            //.Add("CreateDept", "=")
            //.Add("UpdateDept", "=")
            ;

            //工厂处理
            if (_userIdentity.Headoffice)
                where.Add(nameof(CBS_BreakRules.CreateFactory), "="); //总部从查询条件取工厂id
            else
                where.Add(nameof(CBS_BreakRules.CreateFactory), "=", _userIdentity.Factory);

            where.Add(nameof(CBS_BreakRules.CreateUser), "=", _userIdentity.Id);

            //基础查询，联表查询在此操作
            var baseQuery = _repository.QueryBase().AsNoTracking()
                .Include(c => c.CBS_List)
                .Include(c => c.CBS_User)
                .Include(c => c.SysArea);
            loadPageOffsetModel.QueryWhere = where;
            loadPageOffsetModel.Selector = model => new CBS_BreakRules(){
                Id = model.Id,
                CBSListId = model.CBSListId,
                ViolationDate = model.ViolationDate,
                ViolationInstructions = model.ViolationInstructions,
                ViolatorsID = model.ViolatorsID,
                ViolationClause = model.ViolationClause,
                DiscoveringPeopleID = model.DiscoveringPeopleID,
                Remarks = model.Remarks,
                ProcessingOpinion = model.ProcessingOpinion,
                ContractorQZ = model.ContractorQZ,
                CreateFactory = model.CreateFactory,
                CreateDept = model.CreateDept,
                UpdateDept = model.UpdateDept,
                State = model.State,
                CBS_List = model.CBS_List,
                CBS_User = model.CBS_User,
                SysArea = model.SysArea,
            };
            loadPageOffsetModel.BasqQuery = baseQuery.OrderByDescending(x => x.CreateTime);
            return loadPageOffsetModel;
        }

        public async Task<IPageModel<CBS_BreakRulesDto>> GetList(PagingModel<CBS_BreakRulesDto>
            pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }


        public async Task<IPageModel<CBS_BreakRulesDto>> GetApproveList(PagingModel<CBS_BreakRulesDto>
            pagingQueryModel)
        {
            var loadPageOffsetModel = this.GetLoadPageOffsetModelAuto(pagingQueryModel);
            this.GetLoadPageOffsetModel(pagingQueryModel);

            //查询条件
            var whereEntity = pagingQueryModel.Model.ToEntity<CBS_BreakRules>();
            var where = this.CreateQRList()

            .Add("CBSListId", "=")
            .Add("AreaID", "=")
            ;
            //工厂处理
            if (_userIdentity.Headoffice)
                where.Add(nameof(CBS_BreakRules.CreateFactory), "="); //总部从查询条件取工厂id
            else
                where.Add(nameof(CBS_BreakRules.CreateFactory), "=", _userIdentity.Factory);


            //基础查询，联表查询在此操作
            var baseQuery = _repository.QueryBase().AsNoTracking()
                .Include(c => c.CBS_List)
                .Include(c => c.CBS_User)
                .Include(c => c.SysArea)
                .Include(c => c.CBS_BreakRulesApprove);
            loadPageOffsetModel.QueryWhere = where;
            loadPageOffsetModel.Selector = model => new CBS_BreakRules()
            {
                Id = model.Id,
                CBSListId = model.CBSListId,
                ViolationDate = model.ViolationDate,
                ViolationInstructions = model.ViolationInstructions,
                ViolatorsID = model.ViolatorsID,
                ViolationClause = model.ViolationClause,
                DiscoveringPeopleID = model.DiscoveringPeopleID,
                Remarks = model.Remarks,
                ProcessingOpinion = model.ProcessingOpinion,
                ContractorQZ = model.ContractorQZ,
                CreateFactory = model.CreateFactory,
                CreateDept = model.CreateDept,
                UpdateDept = model.UpdateDept,
                State = model.State,
                CBS_List = model.CBS_List,
                CBS_User = model.CBS_User,
                SysArea = model.SysArea,
                CBS_BreakRulesApprove = model.CBS_BreakRulesApprove,
            };
            loadPageOffsetModel.BasqQuery = baseQuery.OrderByDescending(x => x.CreateTime);

            //当前用户未审核判断
            string SysDutyID = "";
            System.Data.DataTable dt = _helper.ExecuteDataTable("SELECT [SysDutyID] FROM [SysUserDuty] where IsDeleted = 0 and [SysUserId]= '" + _userIdentity.Id.ToString() + "' ", null);
            if (dt != null && dt.Rows.Count > 0)
            {
                SysDutyID = dt.Rows[0]["SysDutyID"].ToString();
            }

            System.Data.DataTable dt1 = _helper.ExecuteDataTable("select distinct tc.Id from CBS_BreakRulesApprove tcha left join CBS_BreakRules tc on tcha.BreakRulesId=tc.Id where (tc.State='2' and tcha.ExamineUser='" + _userIdentity.Id + "' and tcha.ExamineOrder = 1 and tcha.ExamineState =  '0' and tcha.IsDeleted=0) or ((tc.State='3' or tc.State='4') and tcha.ExamineDuty='" + SysDutyID + "' and tcha.ExamineOrder = 2 and tcha.ExamineState =  '0' and tcha.IsDeleted=0)  or (tc.State='5' and tcha.ExamineDuty='" + SysDutyID + "' and tcha.ExamineOrder = 3 and tcha.ExamineState =  '0' and tcha.IsDeleted=0) ", null);
            List<Guid> ids = new List<Guid>();
            if (dt1 != null && dt1.Rows.Count > 0)
            {
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    ids.Add(Guid.Parse(dt1.Rows[i]["Id"].ToString()));

                }
            }

            loadPageOffsetModel.BasqQuery = loadPageOffsetModel.BasqQuery.Where(m => (ids.Contains(m.Id)));
            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }


        public async Task<CBS_BreakRules> GetAsync(Guid id)
        {
            var basqQuery = _repository.QueryBase().AsNoTracking()
                .Include(c => c.CBS_List)
                .Include(c => c.CBS_User)
                .Include(c => c.SysArea)
                .Include(c => c.CBS_BreakRulesApprove)
                .Include(c => c.CBS_BreakRulesAttachment)
                .Include(c => c.CBS_BreakRulesAttachment).ThenInclude(u => u.SysUser).ThenInclude(u => u.SysUserInfor);
            return await base.GetAsync(id, basqQuery);
        }

        public async Task<CBS_BreakRulesDto> UpdateAsync(CBS_BreakRulesDto dto, bool autoSave = true, List<string> noUpdateProperties = null)
        {
            var removeList = _repository._dbContext.CBS_BreakRulesAttachment.Where(c => c.BreakRulesId == dto.Id);
            var removeList_Approve = _repository._dbContext.CBS_BreakRulesApprove.Where(c => c.BreakRulesId == dto.Id);
            _repository._dbContext.RemoveRange(removeList);
            _repository._dbContext.RemoveRange(removeList_Approve);
            return await base.UpdateAsync(dto);
        }

        public async Task<string>
            Export(PagingModel<CBS_BreakRulesDto>
                pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            var DataList = await this.ExportDataAsync(loadPageOffsetModel);
            var excelData = DataList.Select(model => new
            {
                model.CBS_List.ContractorName,
                ContractorName_title = "承包商",
                model.ViolationDate,
                ViolationDate_title = "违规日期",
                model.ViolationInstructions,
                ViolationInstructions_title = "违规情况说明",
                model.CBS_User.PersonnelName,
                PersonnelName_title = "违规人",
                model.ViolationClause,
                ViolationClause_title = "违规条款",
                model.SysArea.Name,
                Name_title = "发现区域",
                model.DiscoveringPeople,
                DiscoveringPeople_title = "发现人",
                model.Remarks,
                Remarks_title = "备注",
                //model.ProcessingOpinion,
                //ProcessingOpinion_title = "处理意见",
                //model.ProcessingResult,
                //ProcessingResult_title = "处理结果",
                //model.ExamineState,
                //ExamineState_title = "审批结果",
                //model.ExamineUser,
                //ExamineUser_title = "审批用户",
                //model.ContractorQZ,
                //ContractorQZ_title = "承包商违章签字",
                //model.CreateFactory,
                //CreateFactory_title = "隶属工厂",
                //model.CreateDept,
                //CreateDept_title = "添加部门",
                //model.UpdateDept,
                //UpdateDept_title = "更改部门",
            }).ToList();

            return _excelHelp.Create(excelData);
        }

    }

}
